from web3 import Web3

w3 = Web3(Web3.HTTPProvider('https://mainnet.infura.io/v3/f3fde5c8dc7a42d99214014edbebb793'))

def get_gas_price():
    gas_price = w3.eth.gas_price
    print(f'gas_price number: {gas_price}')
    return gas_price

def getTransactionHistory(address):
    balance = w3.eth.get_balance(address)
    print(f'Balance: {w3.from_wei(balance, "ether")} ETH')
    print(f'转：{w3.eth.get_transaction_count(address)}')

    blockNumber = w3.eth.block_number
    print(f'Current block number: {blockNumber}')

    # transactions = []
    # for i in range(10):
    #     block = w3.eth.get_block(blockNumber - i, True)
    #     if len(block.transactions) > 0:
    #         for tx in block.transactions:
    #             if address == tx['to'] or address == tx['from']:
    #                 transactions.append(tx)

    # print(f'Total transactions: {len(transactions)}')
    # print(transactions)

# 定义一个函数，接受两个参数：地址和以太坊数量
def transfer_eth(address, amount):
    # 创建一个web3对象，连接到本地节点
    w3 = Web3.Web3(Web3.Web3.HTTPProvider('http://localhost:8545'))
    # 设置我的账号地址和私钥，这里只是示例，你应该用自己的账号和私钥
    my_address = '0x123456789abcdef0123456789abcdef012345678'
    my_private_key = '0xabcdef0123456789abcdef0123456789abcdef0123456789abcdef0123456789'
    # 转换以太坊数量为wei单位，1 ether = 10**18 wei
    amount_in_wei = w3.toWei(amount, 'ether')
    # 获取当前的交易数，用于生成交易
    nonce = w3.eth.getTransactionCount(my_address)
    # 构造一个交易字典，包含发送方，接收方，交易数，金额，手续费等信息
    tx_dict = {
        'from': my_address,
        'to': address,
        'nonce': nonce,
        'value': amount_in_wei,
        'gas': 21000, # 这是转账交易的固定手续费
        'gasPrice': w3.toWei('50', 'gwei') # 这是每个单位手续费的价格，可以根据市场情况调整
    }
    # 使用私钥对交易进行签名，得到一个原始交易
    signed_tx = w3.eth.account.signTransaction(tx_dict, my_private_key)
    # 发送原始交易到以太坊网络，得到一个交易哈希
    tx_hash = w3.eth.sendRawTransaction(signed_tx.rawTransaction)
    # 打印交易哈希
    print(f'Transaction hash: {tx_hash.hex()}')


checksum_address = Web3.to_checksum_address('0x0eee1bbb6a0d643211238e1fdf24ce7b3c29a7fe')
get_gas_price()
getTransactionHistory(checksum_address)